package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

func main() {
	// 初始化
	max := 20     // 设置猜数字答案的范围
	counter := 10 // 猜数字的人数
	ch := make(chan int)
	//idCh := make(chan int, 1)
	answer := rand.Intn(max)
	fmt.Println("answer for guess num game is: ", answer)
	fmt.Println("---------------------------------------")

	wg := sync.WaitGroup{}

	// 核心代码
	wg.Add(counter)
	counTmp := counter
	for i := 1; i <= counter; i++ {
		go func(ii int) {
			defer wg.Done()
			result := rand.Intn(max)

			fmt.Println("Player No.", ii, " guess ", result)
			if result == answer {
				ch <- result
			}
		}(i)
	}

	wg.Add(1)

	go func() {
		defer wg.Done()
		//counTmp := counter
		//flag := true

		for {
			//if counTmp == 0 {
			//	if flag == true {
			//		time.Sleep(time.Second * 1)
			//		fmt.Println("no player guess the answer, game over...")
			//		return
			//	} else {
			//		time.Sleep(time.Second * 1)
			//		fmt.Println("someone guess the answer, game over...")
			//		return
			//	}
			//}
			if counTmp == 0 {
				time.Sleep(1 * time.Second)
				break
			}

			// 判断是否猜对
			select {
			case res := <-ch:
				fmt.Println("Someone guess success, result is ", res)
				//counTmp--
				//flag = false
				counTmp--
			default:
				//counTmp--
				fmt.Println("Someone guess fail")
				counTmp--
			}
		}
	}()

	wg.Wait()
	fmt.Println("---------------------------------------")
}

//
//import "fmt"
//
//func main() {
//	mp1 := map[string]int{
//		"hhh":       1,
//		"hehehe":    2,
//		"chachacha": 3,
//	}
//
//	for val, exists := range mp1 {
//		fmt.Println(val, "   ", exists)
//	}
//
//	const (
//		PartSubject = "subject"
//		PartTags    = "tags"
//		PartViews   = "views"
//	)
//	stopChs := map[string]chan struct{}{
//		PartSubject: make(chan struct{}),
//		PartTags:    make(chan struct{}),
//		PartViews:   make(chan struct{}),
//	}
//
//	for part := range stopChs {
//		fmt.Println(part)
//	}
//}
